<template>
  <div class="popup-rules-tab">
    <!-- 搜索和操作区域 -->
    <div class="tab-header">
      <div class="search-area">
        <el-form :model="searchForm" class="search-form" inline>
          <el-form-item label="触发类型">
            <el-select v-model="searchForm.triggerType" placeholder="全部类型" style="width: 140px;" clearable>
              <el-option label="立即触发" value="immediate" />
              <el-option label="延迟触发" value="delay" />
              <el-option label="退出意图" value="exit_intent" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" style="width: 120px;" clearable>
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="action-area">
        <el-button type="primary" @click="$emit('create', 'add')">
          <el-icon><Plus /></el-icon>
          新增规则
        </el-button>
        <el-button @click="$emit('refresh')">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 规则列表 -->
    <div class="rules-list">
      <el-table 
        :data="filteredRules" 
        border 
        style="width: 100%"
        v-loading="loading"
        empty-text="暂无规则数据"
      >
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="description" label="规则描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="triggerType" label="触发类型" width="120">
          <template #default="scope">
            <el-tag :type="getTriggerTypeTagType(scope.row.triggerType)">
              {{ getTriggerTypeText(scope.row.triggerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="触发条件" width="200">
          <template #default="scope">
            <div class="trigger-conditions">
              <div>用户: {{ getUserTypeText(scope.row.showConditions.userType) }}</div>
              <div>设备: {{ getDeviceTypeText(scope.row.showConditions.deviceType) }}</div>
              <div v-if="scope.row.delaySeconds">延迟: {{ scope.row.delaySeconds }}秒</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="频率限制" width="150">
          <template #default="scope">
            <div class="frequency-limit">
              <div>{{ scope.row.frequencyLimit.maxShows }}次</div>
              <div>{{ getPeriodText(scope.row.frequencyLimit.period) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="$emit('edit', scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Plus, Refresh } from '@element-plus/icons-vue'
import type { Site, PopupRule, Coupon } from '@/types/sitePopup'

// Props
interface Props {
  rules: PopupRule[]
  loading: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  refresh: []
  create: ['add' | 'edit']
  edit: [PopupRule]
  delete: [string]
}>()

// 响应式数据
const searchForm = ref({
  triggerType: '',
  status: ''
})

const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 计算属性
const filteredRules = computed(() => {
  let result = [...props.rules]
  
  if (searchForm.value.triggerType) {
    result = result.filter(item => item.triggerType === searchForm.value.triggerType)
  }
  
  if (searchForm.value.status) {
    result = result.filter(item => item.status === searchForm.value.status)
  }
  
  total.value = result.length
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 监听规则数据变化
watch(() => props.rules, () => {
  total.value = props.rules.length
  currentPage.value = 1
}, { immediate: true })

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const resetSearch = () => {
  searchForm.value = {
    triggerType: '',
    status: ''
  }
  currentPage.value = 1
}

const handleDelete = (id: string) => {
  emit('delete', id)
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

const getTriggerTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'immediate': 'success',
    'delay': 'warning',
    'exit_intent': 'danger'
  }
  return typeMap[type] || 'info'
}

const getTriggerTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'immediate': '立即触发',
    'delay': '延迟触发',
    'exit_intent': '退出意图'
  }
  return typeMap[type] || type
}

const getUserTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'all': '全部用户',
    'new': '新用户',
    'returning': '老用户',
    'vip': 'VIP用户'
  }
  return typeMap[type] || type
}

const getDeviceTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'all': '全部设备',
    'desktop': '桌面端',
    'mobile': '移动端'
  }
  return typeMap[type] || type
}

const getPeriodText = (period: string) => {
  const periodMap: Record<string, string> = {
    'session': '会话内',
    'day': '每日',
    'week': '每周',
    'month': '每月'
  }
  return periodMap[period] || period
}
</script>

<style scoped>
.popup-rules-tab {
  padding: 20px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 20px;
}

.search-area {
  flex: 1;
}

.search-form {
  margin: 0;
}

.action-area {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.rules-list {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.trigger-conditions {
  font-size: 12px;
  line-height: 1.4;
}

.trigger-conditions > div {
  margin-bottom: 2px;
}

.frequency-limit {
  font-size: 12px;
  line-height: 1.4;
  text-align: center;
}

.frequency-limit > div {
  margin-bottom: 2px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 12px;
}
</style>
